/**
     *
     */

package com.xyz.frame.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xyz.frame.bean.app.param.PayParam;
import com.xyz.frame.bean.model.User;
import com.xyz.frame.bean.pay.PayInfoDto;
import com.xyz.frame.security.api.model.XyzUser;
import com.xyz.frame.security.api.util.SecurityUtils;
import com.xyz.frame.service.PayService;
import com.xyz.frame.service.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import com.xyz.frame.common.response.ServerResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * 
 */
@RestController
@RequestMapping("/p/order")
@Tag(name = "订单接口")
@AllArgsConstructor
@Slf4j
public class PayController {

    private final PayService payService;

    private final UserService userService;

    /**
     * 支付接口
     */
    @PostMapping("/pay")
    @Operation(summary = "根据订单号进行支付" , description = "根据订单号进行支付")
    public ServerResponseEntity<Void> pay(@RequestBody PayParam payParam) {
        XyzUser user = SecurityUtils.getUser();
        String userId = user.getUserId();


        PayInfoDto payInfo = payService.pay(userId, payParam);
        payService.paySuccess(payInfo.getPayNo(), "");
        return ServerResponseEntity.success();
    }

    /**
     * 普通支付接口
     */
    @PostMapping("/normalPay")
    @Operation(summary = "根据订单号进行支付" , description = "根据订单号进行支付")
    public ServerResponseEntity<Boolean> normalPay(@RequestBody PayParam payParam) {

        XyzUser user = SecurityUtils.getUser();
        String userId = user.getUserId();
        PayInfoDto pay = payService.pay(userId, payParam);

        // 根据内部订单号更新order settlement
        payService.paySuccess(pay.getPayNo(), "");

        return ServerResponseEntity.success(true);
    }


    /**
     * 无订单支付接口
     */
    @PostMapping("/noOrderPay")
    @Operation(summary = "无订单支付接口" , description = "无订单支付接口")
    public ServerResponseEntity<String> noOrderPay(@RequestBody PayParam payParam) {
        payParam.setMoney("0.01");

        XyzUser user = SecurityUtils.getUser();
        String userId = user.getUserId();
        PayInfoDto pay = payService.noOrderPay(userId, payParam);

        // 根据内部订单号更新order settlement
//        payService.paySuccess(pay.getPayNo(), "");

        return ServerResponseEntity.success(pay.getBody());
    }

    @RequestMapping(value = "/noOrderPayAlipayNotify", method = RequestMethod.POST)
//    @OperationLog(name = "noOrderPayAlipayNotify")
//    @ApiOperation(value = "noOrderPay支付宝支付回调", response = String.class)
    public String noOrderPayAlipayNotify(HttpServletRequest request) {
        try {
            log.info("支付宝支付回调");
            // 回调函数，也就是在支付成功之后，可以调用我们支付之后需要执行的相关方法，从而达到数据库的数据和我们的操作相统一。
            Map<String,String> params = Maps.newHashMap();
            Map requestParams = request.getParameterMap();
            log.info("支付宝回调,requestParams参数:{}", requestParams.toString());
            for(Iterator iter = requestParams.keySet().iterator(); iter.hasNext();){
                String name = (String)iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for(int i = 0 ; i <values.length;i++){
                    valueStr = (i == values.length -1)?valueStr + values[i]:valueStr + values[i]+",";
                }
                params.put(name,valueStr);
            }
            log.info("支付宝回调,sign:{},trade_status:{},参数:{}",params.get("sign"),params.get("trade_status"),params.toString());
//            PaySuccessOrder order = paySuccessTypeFactory.getFactory(Integer.valueOf(params.get("orderType"))).getOrder(params.get("out_trade_no"));
//            if(order.getPayStatus().intValue() == OrderPayStatusEnum.SUCCESS.getValue().intValue()){
//                return "success";
//            }
            // 非常重要，验证回调的正确性，是不是支付宝发的。并且呢还要避免重复通知。
            // 因为支付宝要求我们除去两个参数 sign（rsaCheckV2函数已经帮我们除去）、sign_type（自己手动除去）
            params.remove("sign_type");
//            String orderType = params.get("orderType");
//            String paySource = params.get("paySource");
//            String ple = params.get("ple");
            String userId = params.get("userId");
            // 附加的参数
//            params.remove("orderType");
//            params.remove("paySource");
//            App app = appService.getById(order.getAppId());
//            log.info("===>alipayNotify=>app:{}",app);
            // RSA2
            // 第二参数注意是支付宝公共密钥，而不是应用密钥
            // 这里编码是与 new AlipayTradeServiceImpl.ClientBuilder().build(); 里的编码一样，build() 默认为UTF-8，当然也可以自定义，但是只要保证两个一样即可，我们统一保持UTF-8
//            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, app.getAlipayPublickey(),"utf-8", "RSA2");
//            log.info("===>alipayNotify=>alipayRSACheckedV2:{}",alipayRSACheckedV2);

//            if(!alipayRSACheckedV2){
//                log.info("支付宝回调验签失败");
//                return "error";
//            }
            log.info("支付宝回调验签成功!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            // 加入自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            JSONObject attach = new JSONObject();
//            attach.put("orderType", orderType);
//            attach.put("paySource", paySource);
//            attach.put("multiple", ple);
            attach.put("userId", userId);
//            PayDataVo payDataVo = new PayDataVo();
//            payDataVo.setTransaction_id(params.get("trade_no"));
//            payDataVo.setAttach(attach);
            log.info("支付宝支付成功处理");
            User userByUserId = userService.getUserByUserId(userId);
            log.info("===>noOrderPayAlipayNotify=>userByUserId:{}",userByUserId);
            userByUserId.setVipType(2);
            Date date = new Date();
            date.setMonth(date.getMonth()+1);

            userByUserId.setVipExpire(date);
            userService.updateById(userByUserId);
//            paySuccessTypeFactory.getFactory(attach.getInteger("orderType"))
//                    .onPaySuccess(params.get("out_trade_no"), 10, OrderPayTypeEnum.ALIPAY.getValue(), payDataVo);
            return "success";
        } catch (Exception e) {
            log.error("支付宝支付回调异常,异常原因:", e);
            return "error";
        }
    }


    @RequestMapping(value = "/noOrderPayAlipayReturn", method = RequestMethod.GET)
//    @OperationLog(name = "noOrderPayalipayReturn")
//    @ApiOperation(value = "支付宝支付回调", response = String.class)
    public void noOrderPayAlipayReturn(HttpServletRequest request, HttpServletResponse response) {
        try {
            log.info("支付宝支付回调return");
            // 回调函数，也就是在支付成功之后，可以调用我们支付之后需要执行的相关方法，从而达到数据库的数据和我们的操作相统一。
            Map<String,String> params = Maps.newHashMap();
            Map requestParams = request.getParameterMap();
            log.info("支付宝支付回调return,requestParams参数:{}", requestParams.toString());
            for(Iterator iter = requestParams.keySet().iterator(); iter.hasNext();){
                String name = (String)iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for(int i = 0 ; i <values.length;i++){
                    valueStr = (i == values.length -1)?valueStr + values[i]:valueStr + values[i]+",";
                }
                params.put(name,valueStr);
            }
            log.info("支付宝支付回调return,sign:{},trade_status:{},参数:{}",params.get("sign"),params.get("trade_status"),params.toString());
            // 非常重要，验证回调的正确性，是不是支付宝发的。并且呢还要避免重复通知。
            // 因为支付宝要求我们除去两个参数 sign（rsaCheckV2函数已经帮我们除去）、sign_type（自己手动除去）
            params.remove("sign_type");
            String orderType = params.get("orderType");
            String paySource = params.get("paySource");
            // 附加的参数
            params.remove("orderType");
            params.remove("paySource");
            // 订单
//            Order order = orderService.detailByTradeNo(params.get("out_trade_no"));
//            // 获取app配置
//            App app = appService.getById(order.getAppId());
            // RSA2
//            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, app.getAlipayPublickey(),"utf-8", "RSA2");
//            if(!alipayRSACheckedV2){
//                log.info("支付宝回调验签失败");
//                return;
//            }
            log.info("支付宝回调return验签成功!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            String url = "http://www.xndpy.com/#/pages/index/index";
//            if(Integer.valueOf(orderType).intValue() == OrderTypeEnum.MASTER.getValue().intValue()){
//                url = url + "pages/order/pay-success/pay-success?orderId=" + order.getOrderId();
//            }
            response.sendRedirect(url);
        } catch (Exception e) {
            log.error("支付宝支付回调异常,异常原因:", e);
        }
    }
}
